/**
 * Notes: 门店模块业务逻辑 - 宠物门店预约小程序
 * Date: 2025-01-27 
 */

const BaseService = require('./base_service.js');
const StoreModel = require('../model/store_model.js');
const ServiceModel = require('../model/service_model.js');
const EmployeeModel = require('../model/employee_model.js');
const DeviceModel = require('../model/device_model.js');
const FosterRoomModel = require('../model/foster_room_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class StoreService extends BaseService {

	/**
	 * 获取门店列表（按地理位置）
	 * @param {number} longitude 经度
	 * @param {number} latitude 纬度
	 * @param {number} radius 搜索半径(km)
	 * @returns {Array} 门店列表
	 */
	async getStoreList(longitude, latitude, radius = 10) {
		let where = {
			status: StoreModel.STATUS.OPEN
		};
		let fields = '_id,storeId,name,address,location,phone,openingHours,coverImage,doorLockId,status';
		let orderBy = { createTime: -1 };
		
		const stores = await StoreModel.getAll(where, fields, orderBy, 100, false);
		// 计算距离并过滤
		const nearbyStores = stores.filter(store => {
			// 检查门店是否有位置信息（支持两种数据结构）
			let storeLat, storeLng;
			
			if (store.location && store.location.latitude && store.location.longitude) {
				// 新格式：location对象
				storeLat = store.location.latitude;
				storeLng = store.location.longitude;
			} else if (store.latitude && store.longitude) {
				// 旧格式：直接字段
				storeLat = store.latitude;
				storeLng = store.longitude;
			} else {
				console.log('门店缺少位置信息:', store.name || store._id);
				return false;
			}
			
			const distance = this.calculateDistance(
				latitude, longitude,
				storeLat, storeLng
			);
			
			store.distance = distance;
			console.log(`门店 ${store.name} 距离: ${distance}km`);
			return distance <= radius;
		});
		
		// 按距离排序
		nearbyStores.sort((a, b) => a.distance - b.distance);
		return nearbyStores;
	}

	/**
	 * 获取门店详情
	 * @param {string|number} storeId 门店ID（支持数字ID或ObjectId）
	 * @returns {Object} 门店详情
	 */
	async getStoreDetail(storeId) {
		console.log('=== getStoreDetail 开始 ===');
		console.log('传入的门店ID:', storeId, '类型:', typeof storeId);
		
		// 直接使用传入的门店ID，不进行映射转换
		console.log('直接使用门店_id进行查询:', storeId);
		
		// 获取门店基本信息 - 使用_id字段查询
		let where = { _id: storeId };
		let fields = '_id,storeId,name,address,location,phone,openingHours,coverImage,doorLockId,status,createTime';
		const storeInfo = await StoreModel.getOne(where, fields, {}, false);
		
		if (!storeInfo) {
			throw new Error('门店不存在');
		}

		// 获取门店服务列表
		const services = await this.getStoreServices(storeId);
		
		// 获取门店员工列表
		const employees = await this.getStoreEmployees(storeId);
		
		// 获取门店设备列表
		const devices = await this.getStoreDevices(storeId);

		console.log('门店详情查询结果:', {
			storeInfo: storeInfo ? '存在' : '不存在',
			servicesCount: services ? services.length : 0,
			employeesCount: employees ? employees.length : 0,
			devicesCount: devices ? devices.length : 0
		});
		console.log('=== getStoreDetail 结束 ===');

		return {
			storeInfo,
			services,
			employees,
			devices
		};
	}

	/**
	 * 获取门店服务列表
	 * @param {string|number} storeId 门店ID
	 * @param {string} serviceType 服务类型（可选）
	 * @returns {Array} 服务列表
	 */
	async getStoreServices(storeId, serviceType = null) {
		console.log('=== getStoreServices 开始 ===');
		console.log('传入的门店ID:', storeId, '类型:', typeof storeId);
		console.log('服务类型筛选:', serviceType);
		
		// 直接使用传入的门店ID，不进行映射转换
		console.log('直接使用门店_id进行服务查询:', storeId);
		
		// 查询服务数据 - 使用数组查询，支持一个服务对应多个门店
		// 云数据库中查询数组字段需要使用 in 操作符
		let where = {
			storeIds: storeId, // 查询storeIds数组中包含storeId的服务
			status: ServiceModel.STATUS.ONLINE
		};
		
		// 如果指定了服务类型，添加类型筛选
		if (serviceType) {
			where.serviceType = serviceType;
		}
		
		// 返回新增的寄养房型与容量字段
		let fields = '_id,name,serviceType,description,price,duration,status,roomType,quantity,unit,storeIds';
		let orderBy = { createTime: -1 };
		
		console.log('查询条件:', where);
		const result = await ServiceModel.getAll(where, fields, orderBy, 100, false);
		console.log('查询结果:', result);
		
		// 如果查询结果为空，尝试调试查询
		if (!result || result.length === 0) {
			console.log('查询结果为空，尝试调试查询...');
			// 尝试查询所有服务
			const allServices = await ServiceModel.getAll({ status: ServiceModel.STATUS.ONLINE }, fields, orderBy, 100, false);
			console.log('所有服务数据:', allServices);
			
			// 检查是否有storeIds字段
			if (allServices && allServices.length > 0) {
				console.log('第一个服务的storeIds字段:', allServices[0].storeIds);
			}
		}
		
		console.log('=== getStoreServices 结束 ===');
		
		return result;
	}

	/**
	 * 获取门店寄养房间列表
	 * @param {string|number} storeId 门店ID
	 * @returns {Array} 寄养房间列表
	 */
	async getStoreFosterRooms(storeId) {
		console.log('=== getStoreFosterRooms 开始 ===');
		console.log('传入的门店ID:', storeId, '类型:', typeof storeId);
		
		// 直接使用传入的门店ID，不进行映射转换
		console.log('直接使用门店_id进行寄养房间查询:', storeId);
		
		// 查询寄养房间数据 - 禁用_pid过滤，因为寄养房间数据可能没有_pid字段
		let where = {
			storeId: storeId
		};
		
		let fields = '_id,storeId,roomName,roomType,capacity,price,unit,description,features,image,status';
		let orderBy = { createTime: -1 };
		
		console.log('查询条件:', where);
		const result = await FosterRoomModel.getAll(where, fields, orderBy, 100, false);
		console.log('查询结果:', result);
		
		// 过滤掉status不为1的房间
		const filteredResult = result.filter(room => !room.status || room.status === 1);
		console.log('过滤后的结果:', filteredResult);
		
		console.log('=== getStoreFosterRooms 结束 ===');
		
		return filteredResult;
	}

	/**
	 * 获取门店员工列表
	 * @param {string} storeId 门店ID
	 * @returns {Array} 员工列表
	 */
	async getStoreEmployees(storeId) {
		let where = {
			storeId: storeId,
			status: EmployeeModel.STATUS.ONLINE
		};
		let fields = '_id,name,title,tags,avatar,status';
		let orderBy = { createTime: -1 };
		
		return await EmployeeModel.getAll(where, fields, orderBy, 100);
	}

	/**
	 * 获取门店设备列表
	 * @param {string} storeId 门店ID
	 * @returns {Array} 设备列表
	 */
	async getStoreDevices(storeId) {
		let where = {
			storeId: storeId
		};
		let fields = '_id,name,status';
		let orderBy = { createTime: -1 };
		
		return await DeviceModel.getAll(where, fields, orderBy, 100);
	}

	/**
	 * 添加门店
	 * @param {Object} storeData 门店数据
	 * @returns {Object} 添加结果
	 */
	async addStore(storeData) {
		let {
			name,
			address,
			location,
			phone,
			openingHours,
			coverImage,
			doorLockId
		} = storeData;

		// 验证必填字段
		if (!name) {
			throw new Error('门店名称为必填项');
		}

		let data = {
			_id: this.generateId(),
			name: name,
			address: address || '',
			location: location || {},
			phone: phone || '',
			openingHours: openingHours || '09:00-22:00',
			coverImage: coverImage || '',
			doorLockId: doorLockId || '',
			status: StoreModel.STATUS.OPEN,
			createTime: timeUtil.time(),
			updateTime: timeUtil.time()
		};

		await StoreModel.insert(data);
		return data;
	}

	/**
	 * 更新门店信息
	 * @param {string} storeId 门店ID
	 * @param {Object} storeData 门店数据
	 * @returns {Object} 更新结果
	 */
	async updateStore(storeId, storeData) {
		let where = { _id: storeId };

		// 检查门店是否存在
		let store = await StoreModel.getOne(where);
		if (!store) {
			throw new Error('门店不存在');
		}

		let updateData = {
			updateTime: timeUtil.time()
		};

		// 只更新传入的字段
		if (storeData.name !== undefined) updateData.name = storeData.name;
		if (storeData.address !== undefined) updateData.address = storeData.address;
		if (storeData.location !== undefined) updateData.location = storeData.location;
		if (storeData.phone !== undefined) updateData.phone = storeData.phone;
		if (storeData.openingHours !== undefined) updateData.openingHours = storeData.openingHours;
		if (storeData.coverImage !== undefined) updateData.coverImage = storeData.coverImage;
		if (storeData.doorLockId !== undefined) updateData.doorLockId = storeData.doorLockId;
		if (storeData.status !== undefined) updateData.status = storeData.status;

		await StoreModel.edit(where, updateData);
		return await this.getStoreDetail(storeId);
	}

	/**
	 * 计算两点间距离（公里）
	 * @param {number} lat1 纬度1
	 * @param {number} lon1 经度1
	 * @param {number} lat2 纬度2
	 * @param {number} lon2 经度2
	 * @returns {number} 距离(公里)
	 */
	calculateDistance(lat1, lon1, lat2, lon2) {
		const R = 6371; // 地球半径(公里)
		const dLat = this.deg2rad(lat2 - lat1);
		const dLon = this.deg2rad(lon2 - lon1);
		const a = 
			Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
			Math.sin(dLon/2) * Math.sin(dLon/2);
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		const distance = R * c;
		return Math.round(distance * 10) / 10; // 保留一位小数
	}

	/**
	 * 角度转弧度
	 * @param {number} deg 角度
	 * @returns {number} 弧度
	 */
	deg2rad(deg) {
		return deg * (Math.PI/180);
	}

	/**
	 * 生成唯一ID
	 * @returns {string} 唯一ID
	 */
	generateId() {
		return 'store_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
	}
}

module.exports = StoreService;
